package com.tulingxueyuan.ribbon.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author :tangweiliang
 * @date : 2023/1/29 22:37
 * 未来的你会感谢现在努力的自己
 *
 * 自定义负载均衡策略
 */
public class CustomRule extends AbstractLoadBalancerRule {

    @Override
    public Server choose(Object key) {
        ILoadBalancer loadBalancer = this.getLoadBalancer();

        // 获取当前服务实例
        List<Server> reachableServers = loadBalancer.getReachableServers();
        // 随机获得当前服务的个数
        int random = ThreadLocalRandom.current().nextInt(reachableServers.size());
        Server server = reachableServers.get(random);
        return server;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }
}
